package effects.post
{
	import flash.display.DisplayObject;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.display.BlendMode;
	import flash.geom.ColorTransform;
	import synch.AbstractPostProcessor;
	
	public class RadialBlurEffect extends AbstractPostProcessor
	{	
		private var layers:int = 10;
		public var zoom:Number = 0;
		public var alphaFade:Number = 0;
		private var ct:ColorTransform = new ColorTransform();
		private var clipMatrix:Matrix;
		private var scaleMatrix:Matrix;
		private var outMode:String;
		public var blurOffsetX:Number= 0;
		public var blurOffsetY:Number= 0;	

		private var scale:Number = 1;
		
		private var blendMode:String = null;

		public override function init(output:BitmapData, params:Object=null):void
		{			
			if(params.transparent)
			{
				_input = new BitmapData(output.width, output.height, true, 0);			
			}
			if(params.outMode)
			{
				outMode = params.outMode;
			}
			if(params.blendMode)
			{
				blendMode = params.blendMode;
				trace("Setting blendmode:"+blendMode);
			}
			super.init(output,params);
			
			
			// Centering matrix
			scaleMatrix = new Matrix();
			if(params.layers)layers=params.layers;
			if(params.zoom)zoom=params.zoom;			
		}
			
		private var resetBlur:Boolean = false;		
		
		public override function play(dt:Number):void
		{
				_input.lock();
				_input.fillRect(_input.rect,0);

				super.play(dt);
				if(alphaFade < 0.01)
				{
					_input.unlock();
					// Short circuit radial blur, should be relatively fast
					buffer.lock();
					buffer.draw(_input,null,null,blendMode);
					buffer.unlock();					
					return;
				}
				
			//	trace("Rendering");
				_input.draw(_input,clipMatrix,null,blendMode);
				ct.alphaMultiplier = alphaFade;
				var i:int = 0;
				while(i<layers)
				{
					var zoomRatio:Number = zoom*i;
					scaleMatrix.a = 1+zoomRatio;
					scaleMatrix.d = 1+zoomRatio;
					scaleMatrix.tx = -((_input.width+blurOffsetX)*zoomRatio*0.5);
					scaleMatrix.ty = -((_input.height+blurOffsetY)*zoomRatio*0.5);
					_input.draw(_input,scaleMatrix,ct,BlendMode.ADD,_input.rect,false);
					i++;
				}
				_input.unlock();
				buffer.lock();							
				buffer.draw(_input, null, null, outMode);
				buffer.unlock();
		};
	}
}